package com.github.binarywang.demo.wechat.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.binarywang.demo.wechat.config.WxMaProperties;
import com.github.binarywang.demo.wechat.model.User;
import com.github.binarywang.demo.wechat.service.WxUserService;
import com.github.binarywang.demo.wechat.utils.JsonUtils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import me.chanjar.weixin.common.exception.WxErrorException;

@RestController
@RequestMapping({ "/wechat/user" })
@EnableConfigurationProperties({ WxMaProperties.class })
public class WxMaUserController {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WxMaService wxService;

	@Autowired
	private WxUserService wxUserService;

	@GetMapping({ "login" })
	public String login(String code) {
		if (StringUtils.isBlank(code)) {
			return "empty jscode";
		}
		try {
			WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
			this.logger.info(session.getSessionKey());
			this.logger.info(session.getOpenid());
			this.logger.info(session.getExpiresin().toString());

			return JsonUtils.toJson(session);
		} catch (WxErrorException e) {
			this.logger.error(e.getMessage(), e);
			return e.toString();
		}
	}

	@GetMapping({ "info" })
	public String info(String sessionKey, String signature, String rawData, String encryptedData, String iv) {
		if (!this.wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
			return "user check failed";
		}

		WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

		User user = new User();
		BeanUtils.copyProperties(userInfo, user);
		user = this.wxUserService.saveUser(user);
		return JsonUtils.toJson(user);
	}
}
